const express = require('express')
const multer = require('multer')
const { fail, success } = require('./utils')
const { readBooks, saveBooks } = require('./dao')
const app = express()

app.use(express.json())

app.get('/api/books', async (req, res) => {
  // console.log(req.query)
  let data = await readBooks(res)
  if (req.query.bookname) {
    data = data.filter(item => item.bookname.includes(req.query.bookname))
  }
  success('查询图书列表成功!', data, res)
})

app.post('/api/books', async (req, res) => {
  // console.log(req.body)
  const { bookname, author, publisher } = req.body
  // if (!bookname) return res.send({ message: 'bookname 是必填项!' })
  // if (!author) return res.send({ message: 'author 是必填项!' })
  // if (!publisher) return res.send({ message: 'publisher 是必填项!' })
  if (!bookname) return fail('bookname 是必填项!', 400, res)
  if (!author) return fail('author 是必填项!', 400, res)
  if (!publisher) return fail('publisher 是必填项!', 400, res)

  const books = await readBooks(res)

  const result = {
    id: books[books.length - 1] ? books[books.length - 1].id + 1 : 1,
    ...req.body,
    createdAt: new Date(),
    updateAt: new Date()
  }
  books.push(result)

  await saveBooks(books, res)

  success('添加图书成功', result, res)
})

app.delete('/api/books/:id', async (req, res) => {
  // console.log('删除图书:', req.params.id)

  const books = await readBooks(res)
  const index = books.findIndex(item => item.id === +req.params.id)
  if (index === -1) return fail('您要删除的图书不存在', 400, res)
  books.splice(index, 1)

  await saveBooks(books, res)
  success('删除图书成功', null, res)
})

app.put('/api/books/:id', async (req, res) => {
  // console.log(req.body)
  // console.log(req.params.id)
  const { bookname, author, publisher } = req.body
  if (!bookname) return fail('bookname 是必填项', 400, res)
  if (!author) return fail('author 是必填项', 400, res)
  if (!publisher) return fail('publisher 是必填项', 400, res)

  const data = await readBooks(res)
  const book = data.find(item => item.id === +req.params.id)
  book.bookname = bookname
  book.author = author
  book.publisher = publisher
  book.updateAt = new Date()

  await saveBooks(data, res)
  success('修改图书成功', book, res)
})

app.get('/api/books/:id', async (req, res) => {
  const data = await readBooks(res)
  const result = data.find(item => item.id === +req.params.id)
  if (result) {
    success('获取图书成功', result, res)
  } else {
    fail('没有找到图书', 400, res)
  }
})

// const upload = multer({ dest: 'imgs/' })
const storage = multer.diskStorage({
  destination: 'imgs/',
  filename(req, file, cb) {
    // console.log(file.originalname)
    cb(null, +new Date() + '.' + file.originalname.split('.').pop())
  }
})
const upload = multer({ storage })

app.post('/uploadimg', upload.single('avatar'), (req, res) => {
  success('上传图片成功!', `/imgs/${req.file.filename}`, res)
})

app.use('/imgs', express.static('./imgs'))

app.listen(3000, () => {
  console.log('服务器已启动 - http://localhost:3000')
})